#include "process.h"
#include <unistd.h>
#include <time.h>
#include <stdlib.h>

//函数指针类型
typedef void (*call_t)(const char*, double, double);

//假设我们现在需要完成一个下载的任务
//首先需要获得需要下载的总量
double total = 1024.0;//假设下载1024.0MB
//double speed[] = 1.0;//假设网速默认1.0
double speed[] = {10.0, 0.5, 0.3, 0.2, 0.1, 0.001};//模拟网速

//回调函数, cb分别可以是下载、上传....
void download(int total, call_t cb)
{
  srand(time(NULL));
  //当前对应的下载量
  double current = 0.0;
  while(current <= total)
  {
    //更新进度
    cb("下载中", total, current);
    if(current >= total) break;
    //下载代码
    int random = rand() % 6;
    usleep(5000);
    current += speed[random];
    if(current >= total) current = total;
  }
}

void upload(int total, call_t cb)
{
  srand(time(NULL));
  //当前对应的下载量
  double current = 0.0;
  while(current <= total)
  {
    //更新进度
    cb("上传中", total, current);
    if(current >= total) break;
    //下载代码
    int random = rand() % 6;
    usleep(5000);
    current += speed[random];
    if(current >= total) current = total;
  }
}

int main()
{
  download(1024.0, FlushProcess);
  printf("download 1024.0MB done\n");
  download(512.0, FlushProcess);
  printf("download 512.0MB done\n");
  download(256.0, FlushProcess);
  printf("download 256.0MB done\n");
  download(128.0, FlushProcess);
  printf("download 128.0MB done\n");
  download(64.0, FlushProcess);
  printf("download 64.0MB done\n");
  upload(500.0, FlushProcess);
  printf("upload 500.0MB done\n");

  return 0;
}
